package com.scud.system.controller;

import com.scud.common.result.Result;
import com.scud.model.system.dto.PermissionDto;
import com.scud.model.system.pojo.Permission;
import com.scud.system.service.PermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/system/permission")
@Slf4j
public class PermissionController {
    private final PermissionService permissionService;

    /**
     * 获取所有权限的树形集合
     *
     * @return
     */
    @GetMapping("/getPermissions")
    @PreAuthorize("hasAuthority('PERMISSION_LIST')")
    public Result<List<Permission>> getPermissions() {
        log.info("获取所有权限的树形集合");
        List<Permission> permissions = permissionService.getPermissions();
        return Result.success(permissions);
    }

    /**
     * 获取 所有权限的树形集合 和 roleId对应的权限id集合
     * allMenus          roleMenuIds
     *
     * @param roleId
     * @return
     */
    @GetMapping("/getAllPermissions/{roleId}")
    @PreAuthorize("hasAuthority('PERMISSION_LIST')")
    public Result<Map<String, Object>> getAllPermissions(@PathVariable Long roleId) {
        log.info("获取所有权限的树形集合和roleId:{}对应的权限id集合", roleId);
        Map<String, Object> map = permissionService.getAllPermissions(roleId);
        return Result.success(map);
    }

    /**
     * 添加权限
     *
     * @param permissionDto
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('PERMISSION_ADD')")
    public Result save(@RequestBody PermissionDto permissionDto) {
        log.info("添加权限:{}", permissionDto);
        permissionService.save(permissionDto);
        return Result.success();
    }

    /**
     * 修改权限
     *
     * @param permissionDto
     * @return
     */
    @PutMapping("/update")
    @PreAuthorize("hasAuthority('PERMISSION_UPDATE')")
    public Result update(@RequestBody PermissionDto permissionDto) {
        log.info("修改权限:{}", permissionDto);
        permissionService.update(permissionDto);
        return Result.success();
    }

    /**
     * 删除权限
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('PERMISSION_DELETE')")
    public Result delete(@PathVariable Long id) {
        log.info("删除权限:{}", id);
        permissionService.deleteById(id);
        return Result.success();
    }
}
